//
//  CTCLoginViewController.m
//  ConsultantVersion
//
//  Created by 李小龙 on 2017/3/27.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCLoginViewController.h"
#import "CTCAnswerQuestionVC.h"
#import "UMessage.h"
#import "AppDelegate.h"

#import <Bugly/Bugly.h>

@interface CTCLoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberField;
@property (weak, nonatomic) IBOutlet UITextField *pwdField;

@end

@implementation CTCLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.q
    [CTCUserModel shareUser].login = NO;
    [CTCUserModel shareUser].cookieID = nil;
    self.view.backgroundColor = HEXCOLOR(0xF9F9F9);
    
//    self.phoneNumberField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.phoneNumberField.placeholder attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
//    
//    self.pwdField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.pwdField.placeholder attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)loginBtnClick {
    
    [self.view endEditing:YES];
    
    if (!_phoneNumberField.text.length) {
        [MBProgressHUD showTipMessageInWindow:@"请输入手机号或密码"];
        return;
    }
    
    if (!_pwdField.text.length ) {
        [MBProgressHUD showTipMessageInWindow:@"请输入密码"];
        return;
    }
    
    NSDictionary *parameters = @{
                                 @"accountId" : _phoneNumberField.text,
                                 @"pwd" : [_pwdField.text hyb_toMD5],
                                 @"deviceType" : @0
                                 };
    
    
//    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kLoginUrl
           parameters:parameters
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  int code = [responseObject[@"code"] intValue];
                  NSString *des = responseObject[@"des"];
                  if (code == 1) {
                      [MBProgressHUD showSuccessMessage:des];
                      [self loginSuccessResponse:responseObject];
                      
                  } else {
                      [MBProgressHUD showErrorMessage:des];
                  }
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"服务器繁忙：%@",error);
                  
                   [Bugly reportError:error];
                  
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
                  
              }
     ];
}


- (void)judgeAnswerStatus
{
    [RequestTool POST:kJudgeNoSubmitAnswerUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject %@", responseObject);
        
        NSInteger code = [responseObject[@"code"] integerValue];
        NSString *des = responseObject[@"des"];
        
                if (code == 1) {
//                    [self dismissViewControllerAnimated:YES completion:nil];
                    //0 没有需要回答的 1 有需要回答的
                    if ([responseObject[@"type"]  integerValue] == 1) {
                        [MBProgressHUD showTipMessageInWindow:responseObject[@"code"]];
                        CTCQuestionModel *model = [CTCQuestionModel yy_modelWithJSON:responseObject[@"data"]];
                        
                        UIStoryboard *story = [UIStoryboard storyboardWithName:@"CTCResponderVC" bundle:nil];
                        CTCAnswerQuestionVC *vc = [story instantiateViewControllerWithIdentifier:@"CTCAnswerQuestionVC"];
                        vc.questionModel = model;
                        vc.isRespoderNoAnswer = YES;
                        
                        __weak typeof(self)weakself = self;
                        vc.answerSuccess = ^(){
                            if (weakself.loginSuccess) {
                                weakself.loginSuccess();
                            }
                            [weakself dismissViewControllerAnimated:YES completion:nil];
                        };
                        
                        CTCNavigationController *nav = [[CTCNavigationController alloc]initWithRootViewController:vc];
                        [self presentViewController:nav animated:YES completion:nil];
                        
                    }
                    else {
                        if (self.loginSuccess) {
                            self.loginSuccess();
                        }
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }
                }
                else {
                    [MBProgressHUD showErrorMessage:des];
                }
//        self.uuid = responseObject[@"data"][@"uuid"];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}


- (void)loginSuccessResponse:(id  _Nullable)response
{
    NSDictionary *data = response[@"data"];
    if (data) {
        NSString *cookieID = data[@"cookieId"];
        [NetManager refreshCookieId:cookieID];
        [CTCUserModel shareUser].cookieID = cookieID;
        [CTCUserModel shareUser].login = YES;
        
        [CTCUserModel shareUser].detailModel = [CTCUserDetailModel yy_modelWithJSON:data];
        
        [self bindAliasWithAccout:data[@"uuid"]];
    }
    

    if (self.isNotLogin) {
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [appDelegate configRootViewController];
    } else {
        [self judgeAnswerStatus];
    }
    
}




// 使用帐号绑定alias
- (void)bindAliasWithAccout:(NSString *)uuid{
    
    if (uuid.length) {
        
        dispatch_queue_t queue = dispatch_queue_create(0, 0);
        dispatch_async(queue, ^{
            
            [UMessage setAlias:uuid type:@"alias" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
                
                if (error) {
                    DeLog(@"set alias err %@", error);
                  
                }else {
                    DeLog(@"set alias successfully--%@" ,responseObject);
                 
                }
                
            }];
        });
    }
    
}


@end
